<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" >
      <el-form-item label="公司名称" prop="name" v-show="showSearch">
        <el-input v-model="queryParams.name" placeholder="请输入公司名称" clearable style="width: 240px" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item v-show="showSearch">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-form-item>
      <!--      <el-form-item >-->
      <!--        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>-->
      <!--      </el-form-item>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-form>
    <el-table v-loading="loading" :data="rowList" @selection-change="handleSelectionChange">
      <el-table-column label="公司名称" prop="name" :width="nameColWidth" align="center" fixed="left"/>
      <el-table-column label="状态" align="center" prop="status" width="150">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="启用"
            inactive-value="停用"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="统一社会信用代码" prop="unifyCode" align="center" width="140" />
      <el-table-column label="法人代表" prop="boss" align="center" width="120" />
      <el-table-column label="注册日期" prop="registerDate" align="center" width="120" />
      <el-table-column label="注册金额" prop="registerAmount" align="center" width="120" />
      <el-table-column label="注册地址" prop="registerLocation" align="center" width="120" />
      <el-table-column label="联系方式" prop="contact" align="center" width="120" />
      <el-table-column label="扫描件证件" prop="image" align="center" :width="imageColWidth">
        <template v-slot:default="scope">
          <image-preview v-for="(item,index) in scope.row.images"
            style="width: 100px; height: 100px; margin-right: 15px"
            :src="item">
          </image-preview>
        </template>
      </el-table-column>
      <el-table-column label="类型" prop="type" width="120" />
      <el-table-column label="创建人" prop="createBy" width="120" align="center"/>
      <el-table-column label="修改人" prop="updateBy" width="120" align="center"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"

          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"

          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
       <el-row>
       <el-col :span="12">
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入公司名称" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="unifyCode">
          <el-input v-model="form.unifyCode" placeholder="请输入统一社会信用代码" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="法人代表" prop="boss">
          <el-input v-model="form.boss" placeholder="请输入法人代表" clearable :style="{width: '100%'}"/>
        </el-form-item>
       </el-col>
       <el-col :span="12">
        <el-form-item label="注册金额" prop="registerAmount">
          <el-input v-model="form.registerAmount" placeholder="请输入注册金额" />
        </el-form-item>
        <el-form-item label="注册地址" prop="registerLocation">
          <el-input v-model="form.registerLocation" placeholder="请输入注册地址" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系方式" />
        </el-form-item>
       </el-col>
       <el-col :span="12">
        <el-form-item label="类型" prop="type">
          <!-- <el-input v-model="form.type" placeholder="请输入类型" /> -->
          <el-select v-model="form.type" placeholder="请选择类型" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in corporationOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>

       </el-col>
      </el-row>
        <el-form-item label="注册日期" prop="registerDate">
          <el-date-picker v-model="form.registerDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
            :style="{width: '100%'}" placeholder="请选择注册日期" clearable></el-date-picker>
        </el-form-item>
       <el-form-item label="上传扫描件证件" prop="image">
          <ImageUpload
            v-model="form.image"
            :limit="5"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, listAll, get, add, update, del } from "@/api/social/examine/company";
import { getDicts } from "@/api/system/dict/data";
import {blurRule, changeRule} from "@/utils/formRules";

export default {
  name: "Company",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      imageColWidth: 150,
      showSearch: true,
      // 总条数
      total: 0,
      // 食材表格数据
      rowList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      nameColWidth: 200,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        contractId: undefined,
        company: undefined,
        leader: undefined,
        contact: undefined,
        status: undefined
      },
      menuOptions:[],
      corporationOptions:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name:blurRule('请输入公司名称'),
        type:changeRule('请选择类型'),
        registerDate:changeRule('请选择注册日期')
      }
    };
  },
  created() {
    this.getList();
    this.getType();
  },
  methods: {
  async getType(){
   const {data} = await getDicts('corporation_status')
   const {data:Data} = await getDicts('corporation_type')
    this.menuOptions = data.map(item=>({label:item.dictLabel,value:item.dictValue}))
    this.corporationOptions = Data.map(item=>({label:item.dictLabel,value:item.dictValue}))
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      list(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        let maxWith = 1;
        let maxNameWidth = 1;
        for (var i = 0; i < response.rows.length; i++) {
          response.rows[i].images = [];
          if (response.rows[i].image != null && response.rows[i].image != undefined) {
            response.rows[i].images = response.rows[i].image.split(",");
          }
          if (response.rows[i].images.length > maxWith) {
            maxWith = response.rows[i].images.length;
          }
          response.rows[i].registerDate= this.transferDate(response.rows[i].registerDate);
          let row = response.rows[i];
          if (row.name != null && row.name.length > maxNameWidth) {
            maxNameWidth = row.name.length;
          }
        }
        this.nameColWidth = this.nameColWidth > maxNameWidth * 20 ? this.nameColWidth : maxNameWidth * 20;
        this.imageColWidth = this.imageColWidth > maxWith * 150 ? this.imageColWidth : maxWith * 150;
        this.rowList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleStatusChange(row) {
      let text = row.status === "启用" ? "启用" : "停用";
      update({
        id: row.id,
        status: row.status
      }).then(response => {
        this.$modal.msgSuccess(text + "成功");
        this.getList();
      });
    },
    transferDate(dateString) {
      var date = new Date(dateString);
      // 获取年、月和日
      var year = date.getFullYear();
      var month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1并补零
      var day = date.getDate().toString().padStart(2, '0'); // 天数补零

      // 构建年-月-日格式的字符串
      var formattedDate = year + '-' + month + '-' + day;
      return formattedDate;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加公司";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      get(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改公司";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            update(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            add(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的公司？').then(function() {
        return del(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
